<template>
  <a-modal width="600px" v-model:visible="visible" title="新增推送素材" unmountOnExit @before-ok="onOk">
    <a-form ref="formRef" :model="form" size="medium" auto-label-width>
      <a-form-item label="素材类型" field="msgType">
        <a-radio-group v-model="form.msgType">
          <a-radio value="text">文字</a-radio>
          <a-radio value="image">图片</a-radio>
        </a-radio-group>
      </a-form-item>
      <a-form-item label="素材文字" field="msgData" v-if="form.msgType == 'text'">
        <a-textarea placeholder="请输入素材文字" v-model="form.msgData" :auto-size="{ minRows: 6 }" />
      </a-form-item>
      <a-form-item label="素材图片" field="image" v-else>
        <a-upload list-type="picture" :custom-request="customRequest" :limit="1" />
      </a-form-item>
      <a-form-item label="事件标识" field="eventKey">
        <a-select placeholder="请选择事件标识" v-model="form.eventKey">
          <a-option v-for="item in buttonList" :key="item.eventKey" :value="item.eventKey">
            {{ item.name }}
          </a-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script setup>
import { wechatMsgAppend, wechatMenuAll } from '@/apis'
import { Message } from '@arco-design/web-vue'
import { reAssign } from '@/utils/common'

defineOptions({ name: 'bottomMenuEdit' })

const emit = defineEmits(['getTableData'])
const formRef = ref()
const visible = ref(false)
const buttonList = ref([])
const form = reactive({
  msgType: 'text',
  eventKey: undefined,
  image: undefined,
  msgData: undefined
})

const getWechatMenuAll = async () => {
  const res = await wechatMenuAll()
  buttonList.value = []
  res.data.forEach((item) => {
    if (item?.type == 'click') {
      buttonList.value.push(item)
    }
    if (item?.subButton?.length > 0) {
      item.subButton.forEach((item2) => {
        buttonList.value.push(item2)
      })
    }
  })
}
getWechatMenuAll()

// 打开编辑框并回显表单值
const addOrEdit = (item) => {
  reAssign(form, item)
  form.msgType = form.msgType ?? 'text'
  item && formRef.value?.validate()
  visible.value = true
}

const customRequest = (option) => {
  form.image = option.fileItem.file
  setTimeout(() => {
    option.onProgress({ percent: 100 })
    option.onSuccess()
  }, 500)
}

// 点击确认添加/编辑
const onOk = async () => {
  const validateResult = await formRef.value?.validate()
  if (validateResult) return false
  const formData = new FormData()
  Object.keys(form).forEach((key) => {
    if (form[key]) {
      formData.append(key, form[key])
    }
  })
  await wechatMsgAppend(formData)
  Message.success('操作成功')
  emit('getTableData')
  return true
}

defineExpose({ addOrEdit })
</script>
